import gradio as gr
from audio.asr_model import asr_decode, splice_chunks
import numpy as np

def transcribe(state, audio_chunk):
    return splice_chunks(state, audio_chunk)


def stop_and_build(state):
    # 当trigger_mode='always_last'触发时（流式输入结束）
    if state is not None and len(state) > 0:
        return np.array([]), asr_decode(state)
    else:
        return np.array([]), ""

with gr.Blocks() as demo:
    state = gr.State(np.array([]))
    audio = gr.Audio(sources=["microphone"], streaming=True)
    text = gr.Textbox()

    audio.stream(
        transcribe,
        [state, audio],
        state,
        show_progress='minimal',
        trigger_mode="always_last"  # 确保最后触发一次处理
    )

    audio.stop_recording(stop_and_build, state, [state, text])
if __name__ == "__main__":
    demo.launch(
        show_error=True  # 显示详细错误
    )